package trabajoISW2.data;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import trabajoISW2.domain.implementations.Book;
import trabajoISW2.domain.implementations.Subject;

public class SubjectDAO extends BaseDAO implements ISubjectDAO {

	public SubjectDAO(){
		
	}
	@Override
	public List<Subject> getSubjects() {

		Query q = getEm().createQuery("Select s FROM Subject s");
		return q.getResultList();

	}

	@Override
	public List<Book> getBookBySubject(String s) {
		Query q1 = getEm().createQuery(
				"Select s FROM Subject s WHERE name LIKE '%" + s + "%')");
		List<Subject> subjects = q1.getResultList();
		List<Book> books;
		if (subjects == null)
			books = null;
		else {
			books = new LinkedList<Book>();
			Subject su;
			Iterator<Subject> it = subjects.iterator();
			while (it.hasNext()) {
				su = it.next();
				books.addAll(su.getBooks());
			}
		}
		return books;

	}

	@Override
	public Subject getSubject(int id) {

		return getEm().find(Subject.class, id);

	}

	@Override
	public Subject createSubject(Subject s) {
		getEm().getTransaction().begin();
		getEm().persist(s);
		getEm().getTransaction().commit();
		getEm().close();
		return s;
	}

	@Override
	public void updateSubject(Subject s) {
		getEm().getTransaction().begin();
		getEm().merge(s);
		getEm().getTransaction().commit();
		getEm().close();

	}

	@Override
	public void deleteSubject(int id) {

		Subject subject = getEm().find(Subject.class, id);
		if (subject != null){
			getEm().getTransaction().begin();
			getEm().remove(subject);
			getEm().getTransaction().commit();
			getEm().close();
		}
	}

}
